﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using SPRA.Helpers;

namespace SPRA
{
    public partial class CopyItemPage : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        ListItemHelper factory;
        string strPrevURL;

        private void btnStart_Click(object sender, EventArgs e)
        {
            var fields = cblFields.Items.Cast<ListItem>()
                .Where(x => x.Selected).Select(x => new Guid(x.Value))
                .ToList();

            SPListItem result = factory.Copy(fields.Count == 0 ? null : fields);

            factory.ReAssignPermissionsAfterCopy(result, SPContext.Current.Web.CurrentUser);

            string redirectedUrl = chbRedirectToEditForm.Checked
                ? String.Format("{0}?ID={1}&IsDlg=1", factory.SourceList.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl, result.ID)
                : strPrevURL;

            //Response.Redirect(redirectedUrl);
            Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //Response.Redirect(strPrevURL);
            Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            string[] items = Request["SelectedItems"] != null ? Request["SelectedItems"].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries) : new string[] { };
            int itemId = Int32.Parse(items.FirstOrDefault());

            var selectedItem = SPContext.Current.ListItem ?? SPContext.Current.List.GetItemById(itemId);
            factory = new ListItemHelper(selectedItem);

            if (btnStart == null)
            {
                btnStart = new Button();
                Controls.Add(btnStart);
            }
            btnStart.Click += btnStart_Click;

            if (btnCancel == null)
            {
                btnCancel = new Button();
                Controls.Add(btnCancel);
            }
            btnCancel.Click += btnCancel_Click;

            if (elTitle == null)
            {
                elTitle = new EncodedLiteral();
                Controls.Add(elTitle);
            }

            if (elStatus == null)
            {
                elStatus = new EncodedLiteral();
                Controls.Add(elStatus);
            }

            if (cblFields == null)
            {
                cblFields = new CheckBoxList();
                Controls.Add(cblFields);
            }

            if (chbRedirectToEditForm == null)
            {
                chbRedirectToEditForm = new CheckBox();
                Controls.Add(chbRedirectToEditForm);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            EnsureChildControls();
            strPrevURL = Page.Request["Source"];

            if (!Page.IsPostBack)
            {
                FillCheckBoxList(factory.SourceItem, cblFields);
            }
        }

        private static void FillCheckBoxList(SPListItem listItem, ListControl checkBoxList)
        {
            foreach (SPField f in listItem.ContentType.Fields)
            {
                if ((f.ReadOnlyField || f.Hidden || f.Id == SPBuiltInFieldId.ContentTypeId || f.Id == SPBuiltInFieldId.ContentType)) continue;

                if (f.ShowInDisplayForm.HasValue && !f.ShowInDisplayForm.Value)
                    continue;

                // TODO: use xpath later
                if (f.SchemaXml.Contains("HideInCopyActionForm"))
                    continue;

                string prefix = string.Empty;
                switch (f.Type)
                {
                    case SPFieldType.Lookup:
                        prefix = "<font size=\"2\" color=blue>[L]</font> ";
                        break;
                    case SPFieldType.User:
                        prefix = "<font size=\"2\" color=blue>[U]</font> ";
                        break;
                }

                string description = string.IsNullOrEmpty(f.Description) || string.IsNullOrEmpty(f.Description.Trim())
                    ? String.Empty
                    : String.Format("<br>&nbsp;&nbsp;<font size=\"2\"><i>{0}</i></font>", f.Description);

                var item = new ListItem
                {
                    Text = string.Format("<b>{0}<font size=\"2\">{1}</font></b>{2}", prefix, f.Title, description),
                    Value = f.Id.ToString(),
                    Selected = true
                };
                checkBoxList.Items.Add(item);
            }
        }
    }
}
